import {getGoodDetailAPI, addToCartOrUpdateAPI} from "@/api/detailApi";

const actions = {
    /* 获取商品详情的actions */
    async fetchGoodDetail(context, id) {
        const {data: goodDetail} = await getGoodDetailAPI(id)
        context.commit("updateGoodDetail", goodDetail)
    },
    /* 将商品添加到购物车的actions（使用async修饰符修饰的函数是一个异步函数，返回一个Promise要么成功要么失败） */
    async addOrUpdateShopCart(context, params) {
        const {code} = await addToCartOrUpdateAPI(params)
        if (code !== 200) return Promise.reject("失败")
        return Promise.resolve("成功")
    }
}
const mutations = {
    /* 更新商品详情的mutations */
    updateGoodDetail(state, goodDetail) {
        state.goodDetail = goodDetail
    }
}
const state = () => {
    return {
        /* 商品详情 */
        goodDetail: {}
    }
}
const getters = {
    /*一级、二级、三级分类的数据 如果服务器还没有返回数据则返回一个空对象*/
    categoryView: state => state.goodDetail.categoryView || {},
    /*产品的信息 如果服务器还没有返回数据则返回一个空对象*/
    skuInfo: state => state.goodDetail.skuInfo || {},
    /* 图片列表 */
    imageList: (state, getters) => getters.skuInfo.skuImageList || [],
    /* */
    spuSaleAttrList: state => state.goodDetail.spuSaleAttrList || []
}
export default {
    actions,
    mutations,
    state,
    getters,
    namespaced: true
}
